
import argparse
import json
import math
import os, cv2

import numpy as np
from tqdm import tqdm


parser = argparse.ArgumentParser('rec')
parser.add_argument("--basepath", type=str, default='E:/data/vin/VIN/rubbing/rubbing~/Rubbing')

parser.add_argument("--imgpath", type=str, default='train_img')
parser.add_argument("--xmlpath", type=str, default='train_gt')
parser.add_argument("--txtsavepath", type=str, default='E:/data/vin/VIN/rubbing/rubbing~/Rubbing/train.txt')

args = parser.parse_args()

def paixu(ps):


    p = [[int(ps[0]),int(ps[1])],[int(ps[2]),int(ps[3])],[int(ps[4]),int(ps[5])],[int(ps[6]),int(ps[7])]]
    p = sorted(p, key=lambda point: point[1])
    sorts = []
    if p[0][0]<p[1][0]:
        sorts.append(p[0])
        sorts.append(p[1])
    else:
        sorts.append(p[1])
        sorts.append(p[0])
    if p[2][0]<p[3][0]:
        sorts.append(p[3])
        sorts.append(p[2])
    else:
        sorts.append(p[2])
        sorts.append(p[3])
    return sorts

f = open(args.txtsavepath, "w", encoding='utf-8')

xml_list = os.listdir(os.path.join(args.basepath,args.xmlpath))

for i in xml_list:
    dic = {"transcription": "TEMPORARY", "points": [[973, 307], [971, 327], [1018, 331], [1019, 316]]}
    imgname = i.split(".")[0]+".jpg"
    if os.path.exists(os.path.join(args.basepath,args.imgpath,imgname)):
        txt = open(os.path.join(args.basepath,args.xmlpath,i),"r",encoding='utf-8').readline().strip()
        points = paixu(txt.split(","))
        dic.update(points=points)
        f.write(os.path.join(args.imgpath,imgname)+"\t"+json.dumps([dic])+"\n")


